import useUserStore from '@s/user.js'
import { getToken } from '@u/auth.js'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import pinia from '../store/pinia.js'
import router from './index.js'
const user = useUserStore(pinia)
NProgress.configure({ showSpinner: false }) // 关闭右边转圈的小圆圈
const whitePath = ['/login']
export default {
  beforeEach: async (to, from, next) => {
    document.title = to.meta.title || 'mt-admin'
    NProgress.start()
    const token = getToken()
    if (!token) {
      if (whitePath.includes(to.path)) {
        return next()
      }
      return next(`/login?redirect=${to.path}`)
    }
    if (to.path === '/login') {
      return next('/')
    }
    const hasRoles = !!user.userInfo.role
    if (!hasRoles) {
      const { role } = await user._getUserInfo(token)
      const asyncRouter = await user.generateRoutes(role)
      asyncRouter.forEach(router.addRoute)
      return next({ ...to, replace: true })
    }

    next()
  },
  afterEach: (to, from, next) => {
    NProgress.done()
  },
}
